var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var onlineUsers = {};
var onlineCount = 0;
app.get('/',function(req,res){
    res.sendFile(__dirname + '/index.html');
})

io.on('connection', function(socket){
    socket.on('login', function(obj){
        console.log(obj)

        socket.name = obj.userid;
        if(!onlineUsers.hasOwnProperty(obj.userid)){
            onlineUsers[obj.userid] = obj.username;
            onlineCount++;
        }

        io.emit('login',{onlineUsers, onlineCount: onlineCount, user:obj});
        console.log(obj.username + '加入了聊天室');
    });

    socket.on('disconnect', function(){
        // 将退出出的人从列表中删除
        if(onlineUsers.hasOwnProperty(socket.name)){
            var obj = { userid: socket.name, username: onlineUsers[socket.name] };

            delete onlineUsers[socket.name];
            onlineCount--;

            io.emit('logout', {onlineUsers, onlineCount: onlineCount, user:obj})
        }
    });

    socket.on('message', function(obj){
        io.emit('message', obj);
    })
})

http.listen(3000, function(){
    console.log('listening on *:3000')
})